import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { TreeModule, TreeNode } from 'primeng/primeng';

import { CudTableService } from 'app/public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../../public/serve/hints/hints.service';
import { InitService } from '../../../../public/serve/init/init.service';
import { Service } from '../../../../server/server';
import { PaginationComponent } from '../../../../public/pagination/pagination.component';
import { Router, ActivatedRoute,ParamMap } from '@angular/router';
import { appProductUrl } from '../../../product.url';
import { product, content } from '../../../product.data';

declare var $: any;

@Component({
    selector: 'app-product-indexing-task-list-product',
    templateUrl: './product-indexing-task-list-product.component.html',
    styleUrls: ['./product-indexing-task-list-product.component.css']
})
export class ProductIndexingTaskListProductComponent implements OnInit {
    treeData: TreeNode[];
    selectedFile: TreeNode[];
    taskId: string;
    searchData: any;

    selectedProduct: Array<object> = [];

    total: number = 0;
    naturalNum: number = 0;
    tabVal: Array<object>;

    isSelectAll: boolean = false;
    isChose: boolean = false;
    projectId:any = '';

    @ViewChild('pagination') pagination: PaginationComponent;
    @Output() taskProductContent = new EventEmitter<void>();

    constructor(
        public initService: InitService,
        private request: CudTableService,
        private hintsService: HintsService,
        public server: Service,
        private route:ActivatedRoute) { }

    isActive = this.server.isActive;
    ngOnInit() {
        this.server.eventEmit.subscribe((value: any) => {
            this.isActive = value;
        });
    }

    async getProductList(taskId,projectId) {
        this.toMogami();
        this.taskId = taskId;
        this.projectId = projectId;
        await this.getTaskProductList();
        await this.getProductTypeTree();
        await this.getMainTaskProductlist();
    }

	/**
	 * 获取主任务产品列表已选数据
	 */
    async getTaskProductList() {
        let params = this.getTaskProductListParams();
        await this.request.postRequest(this.server.baseUrl + appProductUrl.getTaskProductList, params).then((res: any) => {
            if (res.result_code === '0000') {
                for(let item of res.result) {
                    //this.selectedProduct.push(item['productId']);
                }
            } else {
                this.hintsService.messages(res.message, res.result_code);
            }
            return;
        }).catch((err: any) => {
            this.hintsService.messages("error", "error");
            return;
        });
    }

    //获取主任务产品列表数据参数
    getTaskProductListParams() {
        return {
            token: product.retrieval.token,
            pageNo: product.pagination.pageNumber,
            pageSize: 1000,
            taskId: this.taskId,
            queryCriteria: product.retrieval.queryCriteria
        }
    }

    /**
    * 树状图
    */
    async getProductTypeTree() {
        let url = this.server.baseUrl + 'service/producttype/getProParentInfos';
        await this.request.getRequest(url).then((data: any) => {
            if (data.result_code == '0000') {
                this.treeData = data.result;
                this.treeData = this.processTreeData(this.treeData, 'categoryId', 'name');
                return
            } else {
                this.hintsService.messages(data.message, data.result_code);
            }
        }).catch();
    }

    public processTreeData(list: Array<any>, id, name): Array<any> {
        return this.getTreeChildren(list, '0', id, name);
      }
    
      public getTreeChildren(list: Array<any>, parentid: string, id?: string, name?: string): Array<any> {
          let idKey: string = id;
          let labelKey: string = name;
          let result: Array<any> = [];
          for (let item of list) {
              if (item.parentid == parentid) {
                this.fillCSTreeNode(item, item[idKey], item[labelKey]);
                  let children = this.getTreeChildren(list, item[idKey], id, name);
                  if (children && children.length > 0) {
                      item.children = children;
                      item.leaf = false;
                      item.expanded = true;
                  } else {
                      item.leaf = true;
                      item.expanded = false;
                  }
                  result.push(item);
              }
          }
          return result;
      }
    
      public fillCSTreeNode(node: any, data: string, label: string): void {
          node.data = data;
          node.label = label;
          node.expandedIcon = 'fa-minus-square-o';
          node.collapsedIcon = 'fa-plus-square-o';
      }

    /**
     * 展开所有树节点
     */
    _expandAll() {
        this.treeData.forEach(node => {
            this.expandRecursive(node, true);
        });
    }

    // 递归
    expandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.hasOwnProperty('childProductTypeVoList')) {
            node.children = node['childProductTypeVoList'];
            node.children.forEach(childNode => {
                this.expandRecursive(childNode, isExpand);
            });
        }
    }

    // 选中某个树节点
    selectNode(event: any, type) {
        this.treeTopActive = false;
        content.retrieval.categoryId = ''+event.node[type]+'';
        this.getMainTaskProductlist();
    }

    /**
	 * 主任务产品内容列表
	 */
    async getMainTaskProductlist() {
        this.isChose = this.isSelectAll = false;
        let data = this.getMainTaskProductlistParams();
        if(content.retrieval.categoryId){
            data['categoryId'] = content.retrieval.categoryId;
        }
        await this.request.postRequest(this.server.baseUrl +appProductUrl.MainTaskProductlist, data).then((res: any) => {
            if (res.result_code === '0000') {
                this.tabVal = res.data;
                this.total = res.length;
                this.naturalNum = content.pagination.naturalNum;
                this.isSelectAllInCurrent();
            } else {
                this.hintsService.messages(res.message, res.result_code);
            }
            return;
        }).catch((err: any) => {
            this.hintsService.messages("error", "error");
            return;
        });
    }

    //是否选中当前页所有数据
    isSelectAllInCurrent() {
        let index = 0;
        if (this.selectedProduct.length > 0 && this.tabVal.length > 0) {
            for (let item of this.selectedProduct) {
                for (let child of this.tabVal) {
                    if (item === child['productId']) {
                        child['checked'] = true;
                        index++;
                    }
                }
            }
            if (index === this.tabVal.length) {
                this.isChose = this.isSelectAll = true;
            }else {
                this.isChose = this.isSelectAll = false;
            }
        }
    }

    //产品内容列表查询参数
    private getMainTaskProductlistParams() {
        return {
            token: content.retrieval.token,
            pageNo: content.pagination.pageNo,
            pageSize: content.pagination.pageSize,
            taskId: this.taskId,
            productType: Number(this.route.snapshot.queryParams.taskType),//产品
            queryCriteria: this.searchData,
            completestatus: 0,
            projectId : this.projectId
        }
    }

    /**
     * 搜索
     */
    search() {
        this.getMainTaskProductlist();
    }

    changesearch() {
        this.search();
    }

    /**
     * 分页
     * @param pagination 
     */
    _pagination(pagination: Array<any>) {
        content.pagination.pageNo = pagination[0].pageNumber;
        content.pagination.pageSize = pagination[0].pageSize;
        content.pagination.naturalNum = (content.pagination.pageNo - 1) * content.pagination.pageSize;
        this.getMainTaskProductlist();
    }

    /**
     * 单选
     * @param bool
     * @param child
     * @param length
     */
    _chose(bool, child, length) {
        for (let item of this.tabVal) {
            if (item['productId'] === child) {
                item['checked'] = bool;
            }
        }

        if (bool) {
            this.selectedProduct.push(child);
        } else {
            var index = this.selectedProduct.indexOf(child);
            if (index > -1) {
                this.selectedProduct.splice(index, 1);
            }
        }
        this.isSelectAllInCurrent();
    }

    /**
     * 全选
     * @param bool
     * @param tabVal
     */
    _selectAll(bool, list) {
        for (let item of this.tabVal) {
            if (!bool) {
                item['checked'] = false;
                var index = this.selectedProduct.indexOf(item['productId']);
                if (index > -1) {
                    this.selectedProduct.splice(index, 1);
                }
            }

            if (bool) {
                item['checked'] = true;
                var index = this.selectedProduct.indexOf(item['productId']);
                if (index <= -1) {
                    this.selectedProduct.push(item['productId']);
                }
            }
        }
        this.isSelectAll = this.isChose = bool;
    }

    clearData() {
        this.isChose = this.isSelectAll = false;
        this.searchData = '';
        this.selectedProduct = [];
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 20;
        content.pagination.pageNo = 1;
        content.pagination.pageSize = 20;
        content.pagination.naturalNum = 0;
    }

    addTaskProduc() {
        let params = this.getAddTaskProductParams();
        params.productId = this.selectedProduct;
        this.request.postRequest(this.server.baseUrl + appProductUrl.addTaskProduct, params).then((res: any) => {
            if (res.result_code === '0000') {
                this.taskProductContent.emit();
            }
            this.hintsService.messages(res.message, res.result_code);
            this.clearData();
            return;
        }).catch((err: any) => {
            this.clearData();
            this.hintsService.messages("error", "error");
            return;
        });
        
        $("#taskProductList").modal('hide');
    }

    getAddTaskProductParams() {
        return {
            token: content.retrieval.token,
            productId: [],
            taskId: this.taskId,
            updateBy: this.server.getuserName()
        }
    }

    /**
   * 最上级
   * @param id
   */ 
  public treeTopActive:boolean = true;
  toMogami() {
    content.retrieval.categoryId = '';
    this.getMainTaskProductlist();
    this.selectedFile = []
    this.treeTopActive = true;
  }
}

